 <template>
  <div class="box">
     <header class="header cart-top">
        <van-nav-bar
        class="cartNav"
        title="购物车"
         left-arrow
         @click-left='onLeft'
         @click-right="$router.push('/login')">
         <template #right>
             <van-icon name="wap-home-o" @click="$router.push('/home')"/>
            <span class="loginS">登录</span>
          </template>
        </van-nav-bar>
      </header>
      <div class="content cart">
         <van-empty description="空空如也" v-if="flag">
            <van-button round type="danger" class="bottom-button" @click="$router.push('/home')">
              去逛逛
            </van-button>
          </van-empty>
          <div class="" v-else>
            <van-swipe-cell v-for="(item, idx) in cartList" :key="item.proId">
               <van-card
                 :price="item.price"
                 :desc="item.time"
                 :title="item.proName"
                 class="goods-card"
               >
               <template #thumb>
                <van-checkbox v-model="item.flag" @click="selFlag(idx)"></van-checkbox>
                <van-image :src="item.proImg" fit="cover" />
               </template >
               <template #num>
                <van-stepper v-model="item.num" theme="round" button-size="22" @change="change" :name="item.proId"/>
               </template >
               </van-card>
               <template #right>
                 <van-button square text="删除" type="danger" class="delete-button" @click="del(item.proId, idx)"/>
               </template>
             </van-swipe-cell>
             <van-submit-bar :price="priceSum*100" button-text="提交订单" @submit="onSubmit">
               <van-checkbox v-model="allSelFlag">全选</van-checkbox>
               <template #tip>
                 您选择了<span style="font-size: 24px; color: mediumvioletred;">{{proSum}}</span>件商品
               </template>
             </van-submit-bar>
          </div>
      </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { SwipeCell, Card, Button, Empty, Stepper, SubmitBar, Checkbox, Image as VanImage, Toast, NavBar } from 'vant'
import { getCart, getDetail, updateCartNum, delCart, updateFlag, updateAllFlag, addOrder } from '../../api/index.js'
Vue.use(SwipeCell)
Vue.use(Card)
Vue.use(Button)
Vue.use(Empty)
Vue.use(Stepper)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(VanImage)
Vue.use(Toast)
Vue.use(NavBar)
export default {
  beforeRouteEnter (to, from, next) {
    if (localStorage.getItem('isLogin') === 'ok') {
      next()
    } else {
      next('/login')
    }
  },
  data () {
    return {
      cartList: []
    }
  },
  computed: {
    // 利用计算属性,实现空状态和列表的切换
    flag () {
      // 根据数据的长度来计算表
      return this.cartList.length < 1
    },
    // 计算总数量
    proSum () {
      return this.cartList.reduce((prev, next) => {
        if (next.flag) {
          return prev + (next.num - 0)
        } else {
          return prev
        }
      }, 0)
    },
    // 计算总价
    priceSum () {
      return this.cartList.reduce((prev, next) => {
        if (next.flag) {
          return prev + (next.num - 0) * next.price
        } else {
          return prev
        }
      }, 0)
    },
    // 计算全选效果
    allSelFlag: {
      // 通过选中单个商品决定是否选中 全选
      get () {
        return this.cartList.every(val => {
          return val.flag
        })
      },
      // 通过选中行 全选, 决定是否选中 所以商品
      set (val) {
        // console.log(val)
        for (let i = 0; i < this.cartList.length; i++) {
          this.cartList[i].flag = val
        }
        updateAllFlag({
          userId: localStorage.getItem('userId'),
          flag: val
        }).then(res => {
          // console.log('选中状态更新成功')
        })
      }
    }
  },
  methods: {
    onLeft () {
      this.$router.back()
    },
    change (val, detail) {
      // console.log(val, Detail)
      updateCartNum({
        userId: localStorage.getItem('userId'),
        proId: detail.name,
        num: val
      }).then(res => {
        // console.log(res)
      })
    },
    onSubmit () {
      const arr = this.cartList.filter(val => {
        return val.flag
      })
      console.log(arr)
      // 将商品数据中,暂时不用不到的属性,删掉,再加入订单
      addOrder({
        userId: localStorage.getItem('userId'),
        proData: arr
      }).then(res => {
        Toast('添加成功')
        this.$router.push('/order')
      })
    },
    del (id, i) {
      delCart({
        userId: localStorage.getItem('userId'),
        proId: id
      }).then(res => {
        // console.log(res)
        this.cartList.splice(i, 1)
      })
    },
    selFlag (i) {
      updateFlag({
        userId: localStorage.getItem('userId'),
        proId: this.cartList[i].proId,
        flag: this.cartList[i].flag
      }).then(res => {
        // console.log('选中状态更新成功')
      })
    }
  },
  mounted () {
    getCart({
      userId: localStorage.getItem('userId')
    }).then(res => {
      // console.log(data)
      if (res.data.state === 200) {
        // this.cartList = res.data.data.proData
        const arr = res.data.data.proData
        arr.forEach(val => {
          getDetail({
            id: val.proId
          }).then(data => {
            const obj = data.data.data
            obj.num = val.num
            obj.time = val.time + ''
            obj.flag = val.flag
            this.cartList.push(obj)
          })
        })
        console.log(this.cartList)
      } else {
        console.log('购物车空的')
      }
    })
  }
}
</script>

<style lang="scss">
    .van-nav-bar__left{
      .van-icon{
        color: #ccc;
      }
    }
    .van-nav-bar__right{
      display: flex;
      align-items: center;
      // width: 0.3rem;
      height: 0.3rem;
      // border:1px solid red;
      // line-height: 0.3rem;
      margin-top: 0.08rem;
      // margin-right: 0.1rem;
      .loginS{
        color: #e31436;
        width: 100%;
        border: 1px solid red;
        padding: 0 0.02rem;
      }
      .van-icon{
        margin-right: 0.1rem;
        font-size: 18px;
        color:#e31436;
      }
    }
 .delete-button{
      height: 100%;
    }
  .van-checkbox{
        margin-right: 0.1rem;
      }
  .van-card__thumb{
    display: flex;
    width: 1.2rem;
    img{
      width: 88px;
    }
  }
  .van-card {
    padding:20px 16px;
    // background-color: #ccc;
  }
  .van-checkbox__icon{
    .van-icon{
      background:#e31436;
       // color:#e31436;
    }
  }
  .content.cart{
    padding-bottom: 0.2rem 0 1.2rem;
    overflow: auto;
  }
  .van-nav-bar.cartNav{
    border-bottom: 1px solid #aaa;
    box-shadow: 0px 3px 10px 1px #FF0000;
  }
</style>
